package com.example.confirm;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

//单条同步确认
public class SingleSyncConfirm {
    /**
     * 生产者 → 交换机
     * 生产者投递 1条 消息给交换机
     * 交换机持久化,保存本地之后,给生产者一个应答
     * 生产者接收到成功应答之后,再投递下一条消息
     * 10000条,每条都回执一次 总耗时: 1958 毫秒
     * @param args
     */
    private static final String SINGLE_SYNC_CONFIRM_EXCHANGE = "singleSyncConfirmExchange";
    private static final String SINGLE_SYNC_CONFIRM_QUEUE = "singleSyncConfirmQueue";

    public static void main(String[] args) throws IOException, TimeoutException, InterruptedException {
        ConnectionFactory factory = new ConnectionFactory();
        if (true) {
            factory.setHost("localhost");
            factory.setPort(5672);
            factory.setUsername("guest");
            factory.setPassword("guest");
            factory.setVirtualHost("/");
        }
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        //交换机声明
        channel.exchangeDeclare(SINGLE_SYNC_CONFIRM_EXCHANGE, BuiltinExchangeType.DIRECT, true);
        channel.queueDeclare(SINGLE_SYNC_CONFIRM_QUEUE,true,false,false,null);
        channel.queueBind(SINGLE_SYNC_CONFIRM_QUEUE,SINGLE_SYNC_CONFIRM_EXCHANGE,SINGLE_SYNC_CONFIRM_QUEUE);
        /**
         * 开启 confirm 确认
         */
        channel.confirmSelect();

        long begin = System.currentTimeMillis();//开始时间

        for (int i = 0; i < 1000; i++) {
            String str = i + "";
            channel.basicPublish(SINGLE_SYNC_CONFIRM_EXCHANGE,SINGLE_SYNC_CONFIRM_QUEUE,null,str.getBytes());
            //生产者等待确认
            boolean b = channel.waitForConfirms();
            if (b) {
                System.out.println("第 " + i + " 条发送成功");
            } else {
                System.out.println("第 " + i + " 条发送失败================");
            }
        }

        long end = System.currentTimeMillis();//结束时间
        System.out.println("总耗时: " + (end - begin) + " 毫秒");
    }


}
